﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Model.DbModels.Finance;
using TomNet.IMSC.Web.Areas.Finance.Models;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.Finance.Controllers
{
    [Description("管理-金融项属性")]
    public class ItemAttributeController : BaseController
    {
        public IFinanceItemsAttrContract Contract { get; set; }
        public IFinanceItemsContract ItemContract { get; set; }


        [Description("管理-金融项属性列表")]
        public ActionResult Index(int id)
        {
            var entity = ItemContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.ItemId = id;
            ViewData["entity"] = entity;
            return View();
        }
        [Description("管理-金融项属性列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(int pageIndex, int pageSize, int itemId = 0, string search = "")
        {
            var query = Contract.TrackEntities.Where(x => x.FinanceItemsID == itemId);

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<FinanceItemsAttr>().AsQueryable();

            GridData<FinanceItemsAttr> gridData = new GridData<FinanceItemsAttr>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        #region 添加金融项属性
        [Description("管理-添加金融项属性")]
        //[GlobalAuthorization]
        public ActionResult Insert(int id)
        {
            ViewBag.ItemId = id;
            var query = Contract.Entities.Where(x => x.FinanceItemsID == id).OrderByDescending(x => x.Id).Take(1).FirstOrDefault();
            if (query == null)
            {
                //result.Type = AjaxResultType.Error;
                //result.Content = "已经存在相同的用户";
                query = new FinanceItemsAttr();
                query.AttrKey = "k0";
            }
            else
            {
                query.AttrKey = "k" + (int.Parse(StringHelper.RemoveNotNumber(query.AttrKey)) + 1);
            }
            ViewData["entity"] = query;
            initViewData();
            return View();
        }
        private void initViewData()
        {
            //List<SelectListItem> gridData = new List<SelectListItem>();
            ////if (mLogin.Authority == 1)
            //{
            //    gridData.Insert(0, new SelectListItem { Value = "0", Text = "无" });
            //}
            //var data = from n in Contract.TrackEntities// && x.ParentID == 0
            //           select new SelectListItem
            //           {
            //               Value = n.Id + "",
            //               Text = n.AttrKey,
            //           };

            //gridData.AddRange(data);
            ////initDepartAndPosition(null);
            //ViewData["select_parent"] = gridData;
        }

        [Description("管理-添加金融项属性")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult InsertAsync(FinanceItemsAttr entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                //var query = Contract.CheckExists(m => m.AttrKey.Equals(entity.AttrKey)&& m.AttrValue.Equals(entity.AttrValue));
                //if (query)
                //{
                //    result.Type = AjaxResultType.Error;
                //    result.Content = "已经存在相同的用户";
                //}
                //else
                {
                    //if (entity.ParentID == 0)
                    //{
                    //    entity.ShowIndex = Contract.Entities.Where(x => x.ParentID == 0).Count();
                    //}

                    var count = Contract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                        //if (entity.DepId != 0 && entity.IsLiability)
                        //{
                        //    var newuser = Contract.Entities.Where(d => d.UserName == entity.UserName).FirstOrDefault();
                        //    UpdateIsLiability(entity.DepId, newuser.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, newuser.Id);
                        //}

                        //UserInfoModel uiModel = new UserInfoModel();
                        //uiModel.Birthday = DateTime.Parse("1980-01-01");
                        //uiModel.IDNumber = "";//身份证号码
                        //uiModel.Address = "";
                        //uiModel.EMail = "";
                        //uiModel.Education = 0;
                        //uiModel.Nation = 0;//民族
                        //uiModel.PhotoId = 1;
                        //uiModel.Sex = 2;
                        //uiModel.UserId = (from m in Contract.Entities where m.UserName == entity.UserName select m.Id).FirstOrDefault();

                        //UserInfoContract.Insert(uiModel);

                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 修改金融项
        [Description("管理-金融项属性")]
        //[GlobalAuthorization]
        public ActionResult Edit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = Contract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            //initDepartAndPosition(entity);
            ViewData["entity"] = entity;
            initViewData();
            return View();
        }

        [Description("管理-修改属性")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(FinanceItemsAttr entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                //var query = Contract.CheckExists(m => m.AttrKey.Equals(entity.AttrKey) && m.Id != entity.Id);
                //if (query)
                //{
                //    result.Type = AjaxResultType.Error;
                //    result.Content = "已经存在相同的用户";
                //}
                //else
                {
                    ////如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    var count = Contract.Update(entity);
                    if (count > 0)
                    {
                        //if (entity.DepId != 0 && entity.IsLiability == true)
                        //{
                        //    UpdateIsLiability(entity.DepId, entity.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, entity.Id);
                        //}

                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("管理-获取属性值")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditModel(int id)
        {
            var result = new AjaxResult();
            try
            {                
                var query = Contract.GetByKey(id);
                if (query==null)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "获取失败";
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = query;
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        [Description("管理-删除金融项属性")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                //Contract.UpdateDirect(m => idsInt.Contains(m.Id), m => new FinanceItemsAttr { IsDeleted = true });
                Contract.DeleteDirect(m => idsInt.Contains(m.Id));
                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

    }
}